package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.StringUtils;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.cmn.listener.DictListener;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    /**根据数据id查询子数列表**/
    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator" )
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",id);
        List<Dict> list = baseMapper.selectList(queryWrapper);
        //向list集合每个dict对象设置hashchilderen
        for(Dict dict:list){
            Long dictId = dict.getId();
            boolean isChild = this.isChilren(dictId);
            dict.setHasChildren(isChild);
        }
        return list;
    }

    /**导出数据字典**/
    @Override
    public void exportData(HttpServletResponse response) throws IOException {
       //设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
            //这里URLEncoding可以防止中文乱码 和easyexcel没有关系
        String fileName = URLEncoder.encode("数据字典","UTF-8");
        response.setHeader("Content-disposition","attachment;filename="+fileName+".xls");
        //查询数据库
        List<Dict> dictList = baseMapper.selectList(null);
        //Dict转化成DictEeVo
        List<DictEeVo> list = new ArrayList<>();
        for(Dict dict:dictList){
            DictEeVo dictEeVo = new DictEeVo();
            dictEeVo.setId(dict.getId());
            dictEeVo.setName(dict.getName());
            dictEeVo.setDictCode(dict.getDictCode());
            dictEeVo.setValue(dict.getValue());
            dictEeVo.setParentId(dict.getParentId());
            list.add(dictEeVo);
        }
        //调用方法
        EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("dict").doWrite(list);
    }

    /**
     * 导入数据字典
     * @param file
     **/
    @Override
    @CacheEvict(value = "dict",allEntries = true)
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据dictcode和value查询
     *
     * @param dictCode
     * @param value
     **/
    @Override
    public String getDictName(String dictCode, String value) {
        /**如果dictCode为空，直接根据value查询**/
        if(StringUtils.isEmpty(dictCode)){
            /**直接根据value查询**/
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(wrapper);
            return dict.getName();
        }else { //如果dictCode为空，根据dictCode和value查询
            /**如果dictCode不为空，根据dictCode和value查询**/
            Dict codeDict = this.getDictByDictCode(dictCode);
            Long parent_id = codeDict.getId();
            /**根据parat_id和value进行查询**/
            Dict finalDict = baseMapper.selectOne(new QueryWrapper<Dict>()
                    .eq("parent_id", parent_id)
                    .eq("value", value));
            return finalDict.getName();
        }
    }

    /**
     * 根据数据id查询子数据列表
     *
     * @param dictCode
     **/
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //根据dictCode获取相应id
        Dict dict = this.getDictByDictCode(dictCode);
        //根据id获取子节点
        List<Dict> dictlist = this.findChildData(dict.getId());
        return dictlist;

    }

    private Dict getDictByDictCode(String dictCode){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict codeDict = baseMapper.selectOne(wrapper);
        return codeDict;
    }

    /**判断id下面是否有子节点**/
    private boolean isChilren(Long id){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Integer count = baseMapper.selectCount(wrapper);
        return count>0;
    }
}
